package com.itheima.jdbc;

/*
 *  JDBC 快速入门
 * */

import org.junit.Test;

import java.sql.*;

public class JDBCDemo7_PreparedStatement {

    @Test
    public void testDML() throws Exception {

        // 2.获取链接
        String url ="jdbc:mysql://localhost:3306/db1?useSSL=false&serverTimezone=UTC";
        String username ="root";
        String password ="dzl123";
        Connection conn = DriverManager.getConnection(url,username,password);

        // 接受用户输入 用户名和密码
        String name="zhangsan";
        String pwd="123";


        // 定义sql
        String sql="select * from tb_user where username = ? and password= ? ";

        // 获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);

        // 设置？的值
        pstmt.setString(1,name);
        pstmt.setString(2,pwd);

        // 执行sql
        ResultSet rs = pstmt.executeQuery();

        // 判断登录是否成功
        if (rs.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");

        }


        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();

    }
    /*
    * PreparedStatement原理
    * */

    @Test
    public void testDML2() throws Exception {

        // 2.获取链接
        String url ="jdbc:mysql://localhost:3306/db1?useSSL=false&serverTimezone=UTC&useServerPrepStmts=true";
        String username ="root";
        String password ="dzl123";
        Connection conn = DriverManager.getConnection(url,username,password);

        // 接受用户输入 用户名和密码
        String name="zhangsan";

        String pwd="124";


        // 定义sql
        String sql="select * from tb_user where username = ? and password= ? ";

        // 获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);

        // 设置？的值
        pstmt.setString(1,name);
        pstmt.setString(2,pwd);

        // 执行sql
        ResultSet rs = pstmt.executeQuery();

        // 判断登录是否成功
        if (rs.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");

        }


        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();

    }



}
